﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Threading.Tasks;
using System.IO;
namespace bezlimitu.App_Code
{
    public class DownloadLink
    {
        public String Url { get; set; }
        public long Length{get;set;}
        public String Name{get;set;}
        
        public DownloadLink(String Url)
        {
            this.Url = Url;
        }
        
        public void wc_DownloadProgressChanged(Object sender, DownloadProgressChangedEventArgs e)
        {
            System.Diagnostics.Debug.WriteLine(e.ProgressPercentage + "%");
        }
        
        public void DownloadToServer()
        {
            WebClient webClient = new WebClient();
            webClient.DownloadProgressChanged += new DownloadProgressChangedEventHandler(wc_DownloadProgressChanged);
            webClient.DownloadFile(new Uri(Url),"D:\\" + Name + "(1)");
        }

        public void DownloadToClient()
        {
            Stream stream = null;
            int bytesToRead = 20000;
            byte[] buffer = new Byte[bytesToRead];

            try
            {
                HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(Url);
                HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();

                if (fileReq.ContentLength > 0)
                    fileResp.ContentLength = fileReq.ContentLength;

                stream = fileResp.GetResponseStream();

                var resp = HttpContext.Current.Response;

                resp.ContentType = "application/octet-stream";

                resp.AddHeader("Content-Disposition", "attachment; filename=\"" + Name + "\"");
                resp.AddHeader("Content-Length", fileResp.ContentLength.ToString());
                resp.AddHeader("Connection", "Keep-Alive");
                resp.AddHeader("Accept-Ranges", "bytes");
                int length;
                do
                {
                    if (resp.IsClientConnected)
                    {
                        length = stream.Read(buffer, 0, bytesToRead);
                        resp.OutputStream.Write(buffer, 0, length);
                        resp.Flush();
                        buffer = new Byte[bytesToRead];
                    }
                    else
                    {
                        length = -1;
                    }
                } while (length > 0);
            }
            finally
            {
                if (stream != null)
                {
                    stream.Close();
                }
            }

        }
    }
}